package com.yoooya.base.converter;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

/**
 * 日期格式转换
 * 
 * @author Sun Yijing<br />
 *         Copyright © Xiamen Yoooya NetWorks Co.,Ltd.
 * @since yoooya software platform v1.0.0
 * @version 1.0.0 <br />
 *          <table border="1" cellpadding="3" cellspacing="0">
 *          <tr>
 *          <th align="left" colspan="3"><b>修改历史</b></th>
 *          </tr>
 *          <tr>
 *          <td>修改日期</td>
 *          <td>修改人</td>
 *          <td>修改描述</td>
 *          </tr>
 *          <tr>
 *          <td>2018-6-20</td>
 *          <td>Sun Yijing</td>
 *          <td>新建</td>
 *          </tr>
 *          </table>
 */
public class DateConverter extends PropertyEditorSupport implements
		PropertyEditorRegistrar, WebBindingInitializer {

	/**
	 * @Fields format : TODO(日期类型格式,默认格式：yyyy-MM-dd)
	 */
	private String format = "yyyy-MM-dd";

	public void setFormat(String format) {
		this.format = format;
	}

	@Override
	public void registerCustomEditors(PropertyEditorRegistry registry) {
		// TODO Auto-generated method stub
		// 1.将string类型的日期字符串初始化为date类型;
		registry.registerCustomEditor(Date.class, new DateConverter());
		// 2.去除参数两边的空格;
		registry.registerCustomEditor(String.class, new StringTrimmerEditor(
				false));
	}

	@Override
	public void initBinder(WebDataBinder binder, WebRequest request) {
		// 1.将string类型的日期字符串初始化为date类型;
		binder.registerCustomEditor(Date.class, new DateConverter());
		// 2.去除参数两边的空格;
		binder.registerCustomEditor(String.class,
				new StringTrimmerEditor(false));
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		if (StringUtils.isNotEmpty(text)) {
			try {
				date = format.parse(text);
			} catch (ParseException e) {
				format = new SimpleDateFormat("yyyy-MM-dd");
				try {
					date = format.parse(text);
				} catch (ParseException e1) {
					e1.printStackTrace();
				}
			}
		}
		setValue(date);
	}

	public String getFormat() {
		return format;
	}
}